package org.linlinjava.litemall.admin.task;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.admin.job.ShopMerchandiseJob;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallShopMerchandiseJob;
import org.quartz.*;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@RequiredArgsConstructor
public class CronTaskRegistrar{

    private final Scheduler scheduler;

    /**
     * 添加定时任务
     *
     * @param quartzJob
     */
    public ResponseUtil.Response schedulerAdd(LitemallShopMerchandiseJob quartzJob) {
        String cronExpression = StringUtils.trim(quartzJob.getCron());
        String jobKey = getJobKey(quartzJob);
        try {
            // 启动调度器
            scheduler.start();
            // 构建job信息
            JobDetail jobDetail = JobBuilder.newJob(ShopMerchandiseJob.class).withIdentity(jobKey).usingJobData("parameter", quartzJob.getJobName()).build();
            // 表达式调度构建器(即任务执行的时间)
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobKey).withSchedule(scheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            return ResponseUtil.fail(80900,"创建定时任务失败，请更正执行时间为未来的时间");
        } catch (Exception e) {
            return ResponseUtil.fail(80901,"任务创建失败！");
        }
        return ResponseUtil.ok("任务创建成功");
    }

    /**
     * 删除定时任务
     *
     * @param jobKey
     */
    public void schedulerDelete(String jobKey) {
        try {
            scheduler.pauseTrigger(TriggerKey.triggerKey(jobKey));
            scheduler.unscheduleJob(TriggerKey.triggerKey(jobKey));
            scheduler.deleteJob(JobKey.jobKey(jobKey));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("删除定时任务失败");
        }
    }


    private static String getJobKey(LitemallShopMerchandiseJob quartzJob) {
        String jobKey = quartzJob.getId().toString();
        return jobKey;
    }

}
 
 
